#include "udp_client.hpp"

int main(int argc,char* argv[])
{
    if(argc !=3)
    {
        std::cerr << "请输入服务器的ip和端口" << std::endl;
        exit(USEAGE_ERR);
    }
    uint16_t port = htons(atoi(argv[2]));
    std::string ip= argv[1];
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
        std::cerr << "create socket failed" << strerror(errno)<<std::endl;
        exit(SOCKET_ERR);
    }

    //明确server是谁
    struct sockaddr_in server;
    bzero(&server,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = port;
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    socklen_t len= sizeof(server);

    
    //client 不需要自己绑定，os帮client绑定。
    while (1)
    {
        std::string message;
        std::cout << "please enter#" ;
        std::getline(std::cin,message);
        char buffer[1024]= {0};

        //什么时候bind的，在我们首次系统调用发送数据的时候，OS会在底层随机选择clientport+自己的IP,
        //1 bind ,2 构建发送的数据报文
        //发送消息给服务器端
        sendto(sock,message.c_str(),message.size(),0,(struct sockaddr*)&server,len);

        //接受
        struct sockaddr_in peer;
        socklen_t peer_size;
        int n = recvfrom(sock,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&peer_size);
        if(n > 0 ) 
        {
            buffer[n] ='\0';
            std::cout << "server echo#: " << buffer <<std::endl;
        }
    }
    
    return 0;
}